package contextArgs

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func GetUriPath(ctx context.Context, key string) (string, error) {
	s := ctx.(*gin.Context).Param(key)
	if s == "" {
		return "", errors.New("参数不能为空")
	}
	return s, nil
}

func GetUriIntPath(ctx context.Context, key string) (uint, error) {
	s, err := GetUriPath(ctx.(*gin.Context), key)
	if err != nil {
		return 0, err
	}

	integer, err := strconv.Atoi(s)
	if err != nil {
		return 0, errors.New("请求参数错误")
	}

	return uint(integer), err
}

func GetUriQuery(ctx context.Context, key string) (string, error) {
	s := ctx.(*gin.Context).Query(key)
	if s == "" {
		return "", errors.New("参数不能为空")
	}
	return s, nil
}

func GetUriIntQuery(ctx context.Context, key string) (uint, error) {
	s, err := GetUriQuery(ctx, key)
	if err != nil {
		return 0, err
	}

	integer, err := strconv.Atoi(s)
	if err != nil {
		return 0, errors.New("请求参数错误")
	}

	return uint(integer), err
}

func GetAuth(ctx context.Context) (string, error) {
	auth := ctx.(*gin.Context).Request.Header.Get("Authorization")
	if auth == "" {
		return "", errors.New("缺少header信息")
	}

	token := strings.Split(auth, "Bearer ")
	if len(token) == 2 {
		return token[1], nil
	} else {
		return "", errors.New("缺少header信息")
	}
}
